<?php

	$database_address='localhost';
	$database_name='site';
	$database_user='site';
	$database_pass='siteMG';
	define('DATABASE_ADDRESS',$database_address);
	define('DATABASE_NAME',$database_name);
	define('DATABASE_USER',$database_user);
	define('DATABASE_PASS',$database_pass);
	
	function debug($message){
		echo "<pre id='debug' style='background-color:white;color:black;'>";
		echo "		<p>DEBUG:".$message."</p>";
		echo "</pre>";
	}
	function rm_ext($file){
		$file2=explode('.',$file);
		unset($file2[(sizeof($file2)-1)]);
		$file3=implode('.',$file2);
		$nb=strlen($file3);
		if($nb >= 40){
		$file3=substr("$file3",0,40);
		$file3=$file3."...";
		}
		return $file3;
	}
	function refresh(){
		mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
		mysql_select_db(DATABASE_NAME);
		mysql_query("TRUNCATE TABLE `fichier`");
		mysql_close();
		add_fichier("/root/film/");
		//add_fichier("/home/metalgun/Musique/");
	}
	function date_modif($time){
		return date("d/m/y",$time);
	}
	
	function size_modif($size){
		if( $size >'1073741824') {
			$sizegb = (($size / 1024)/1024)/1024;
			$sizegb = round($sizegb,2);
			return "$sizegb Go";
		}elseif($size >'1048576') {
			$sizemb = ($size / 1024)/1024;
			$sizemb = round($sizemb,2);
			return "$sizemb Mo";
		} elseif($size > '1024') {
			$sizekb = $size / 1024;
			$sizekb = round($sizekb,2);
			return "$sizekb Ko";
		}else{
			return "$size o";
		}
	}
	function add_news($titre,$contenu){
		//$titre=addslashes($titre);
		//$contenu=addslashes($contenu);
		$requete="INSERT INTO `site`.`news` (`id` ,`titre` ,`contenu`) VALUES (NULL , '".utf8_decode($titre)."', '".utf8_decode($contenu)."');";
		mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
		mysql_select_db(DATABASE_NAME);
		mysql_query($requete);
		mysql_close();
		echo "<script>alert('News ajouté');</script>";
	}
	function add_user(){
		if($_POST['i_password']!=$_POST['i_password2']){
			echo"<script>alert('Les 2 mots de passe ne concordent pas pour l\'utilisateur ".$_POST['i_login']."');</script>";
		}else{
			mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
			mysql_select_db(DATABASE_NAME);
			$requete="INSERT INTO `site`.`user` (`id` ,`login` ,`password` ,`film` ,`music` ,`admin`)VALUES (NULL , '".$_POST['i_login']."', '".md5($_POST['i_password'])."', '".$_POST['film']."' , '".$_POST['music']."' , '".$_POST['admin']."')";
			mysql_query($requete);
			mysql_close();
			echo "<script>alert('Utilisateur ".$_POST['i_login']." ajouté !')</script>";
		}
	}
	
	function delete_user(){
		mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
		mysql_select_db(DATABASE_NAME);
		$query="DELETE FROM `user` WHERE `login` = '".$_GET['user']."'";
		mysql_query($query);
		mysql_close();
		echo"<script>alert('Utilisateur ".$_GET['user']." Supprimer');</script>";
	}
	function delete_news(){
		mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
		mysql_select_db(DATABASE_NAME);
		$query="DELETE FROM `news` WHERE `id` = '".$_GET['news']."'";
		mysql_query($query);
		mysql_close();
		echo"<script>alert('News n".$_GET['news']." Supprimer');</script>";
	}
	
	function div_accueil(){
		
		echo "<h1 style='color:white;'>Bienvenue sur le site MG Server</h1>";
		echo "<div id='accueil' class='overflow'>";
		if($_GET['page']== 'film'){
			echo "<div id='error'>Vous n'avez pas l'autorisation d'acceder au film</div>";
		}elseif($_GET['page']== 'music'){
			echo "<div id='error'>Vous n'avez pas l'autorisation d'acceder à la musique</div>";
		}elseif($_GET['page']== 'admin'){
			echo "<div id='error'>Vous n'avez pas l'autorisation d'acceder à l'espace administration</div>";
		}else{
			mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
			mysql_select_db(DATABASE_NAME);
			$requete="select * from news order by id DESC";
			$query=mysql_query($requete);
			mysql_close();
			echo "<div id='news'>";
			while ($news = mysql_fetch_array($query) ){
			sscanf($news['time'], "%4s-%2s-%2s %2s:%2s", $annee, $mois, $jour, $heure, $minute); ?>
				
				<h3><?php echo htmlentities(stripslashes($news['titre']));?> <?php echo "<span id='date'>".$jour."/".$mois."/".$annee."</span>";?></h3>
				<p><?php echo htmlentities(stripslashes($news['contenu']));?></p>
				
			<?php 
			}
			echo "</div>";
		}
		echo "</div>";
	}
	function div_admin(){
		?>
		<h1>Administration</h1>
			<div id='admin' class="overflow">
				<div id="refresh"><a href='?page=admin&refresh=1'>Actualisation des Fichiers</a></div>
				<div id="add_user">
					<h2>Ajouter un Utilisateur</h2>
					<form action='index.php?page=admin' method='post'>
					<table>
						<tr><td>Login :</td><td><input type = "text" name="i_login" /></td></tr>
						<tr><td>Password :</td><td><input type="password" name="i_password" /></td></tr>
						<tr><td>Retaper Password :</td><td><input type="password" name="i_password2" /></td></tr>
						<tr><td>Administrateur :</td><td><input type="checkbox"  name="admin" value=1></td></tr>
						<tr><td>Acc&egrave;s au film :</td><td><input type="checkbox" name="film" value=1></td></tr>
						<tr><td>Acc&egrave;s au musique : </td><td><input type="checkbox" name="music" value=1></td></tr>
						<tr><td id="submit"colspan="2"><input type="hidden" name="hidden" value="add_user" /><input type="submit" value="Ajouter" /></td></tr>
					</table>
					</form>
				</div>
				<div id="delete_user">
					<h2>Supprimer un Utilisateur</h2>
					<table>
					<?php
					mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
					mysql_select_db(DATABASE_NAME);
					$requete="select login from user order by id";
					$query=mysql_query($requete);
					mysql_close();
					while ($user = mysql_fetch_array($query) ){
					echo "		<tr><td class='user'>".$user['login']."</td><td><input type='button' value='Supprimer' onClick=\"window.location.replace('?page=admin&user=".$user['login']."&delete=1#delete_user');\"></td></tr>";
					}
					?>
					</table>
				</div>
				<div id="add_news">
					<h2>Ajouter une News</h2>
					<form action='index.php?page=admin' method='post'>
					<table>
						<tr><td>Titre :</td><td><input type = "text" name="i_titre" /></td></tr>
						<tr><td>Contenu :</td><td><textarea cols="50" rows="10" name="i_contenu" ></textarea></td></tr>
						<tr><td id="submit"colspan="2"><input type="hidden" name="hidden" value="add_news" /><input type="submit" value="Ajouter" /></td></tr>
					</table>
					</form>
				</div>
				<div id="delete_news">
					<h2>Supprimer une news</h2>
					<table>
					<?php
					mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
					mysql_select_db(DATABASE_NAME);
					$requete="select id,titre from news order by id";
					$query=mysql_query($requete);
					mysql_close();
					while ($news = mysql_fetch_array($query) ){
					echo "		<tr><td class='user'>".htmlentities($news['titre'])."</td><td><input type='button' value='Supprimer' onClick=\"window.location.replace('?page=admin&news=".$news['id']."&delete=1#delete_news');\"></td></tr>";
					}
					?>
					</table>
				</div>
		</div>
		<?php 
	}
	
	function div_film(){
		mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
		mysql_select_db(DATABASE_NAME);
		$f=htmlspecialchars($_GET['t']);
		$g=strlen($f);
		if($g != 1 and $f !='' and $f !="all" and $f !="recent"){ mysql_close(); die;}
		if ($f == ""){
			$query=mysql_query('Select * from fichier where file like "%.avi" or file like "%.nrg" order by file');
			}
		else if ($f=="all"){
			$query=mysql_query('Select * from fichier where file like "%.avi" or file like "%.nrg" order by file');
			}
		else if ($f=="recent"){
			$query=mysql_query('Select * from fichier where file like "%.avi" or file like "%.nrg" order by time DESC LIMIT 0 , 10');
			}
		else if ($f=="0"){
			$query=mysql_query('Select * from fichier where (file like "0%" or  file like "1%" or  file like "2%" or  file like "3%" or  file like "4%" or  file like "5%" or  file like "6%" or  file like "7%" or  file like "8%" or  file like "9%") and (file like "%.avi" or file like "%.nrg") order by file');
			}
		else{
			$req="Select * from fichier WHERE (file LIKE '".$f."%') and (file like '%.avi' or file like '%.nrg') ORDER BY file ";
			$query = mysql_query($req);
			}
		
		
		echo "<h1>Liste des Films</h1>";
		echo '		<div id="classement"><a href="?page=film&t=all">All</a> <a href="?page=film&t=0">0</a> <a href="?page=film&t=a">A</a> <a href="?page=film&t=b">B</a> <a href="?page=film&t=c">C</a> <a href="?page=film&t=d">D</a> <a href="?page=film&t=e">E</a> <a href="?page=film&t=f">F</a> <a href="?page=film&t=g">G</a> <a href="?page=film&t=h">H</a> <a href="?page=film&t=i">I</a> <a href="?page=film&t=j">J</a> <a href="?page=film&t=k">K</a> <a href="?page=film&t=l">L</a> <a href="?page=film&t=m">M</a> <a href="?page=film&t=n">N</a> <a href="?page=film&t=o">O</a> <a href="?page=film&t=p">P</a> <a href="?page=film&t=q">Q</a> <a href="?page=film&t=r">R</a> <a href="?page=film&t=s">S</a> <a href="?page=film&t=t">T</a> <a href="?page=film&t=u">U</a> <a href="?page=film&t=v">V</a> <a href="?page=film&t=w">W</a> <a href="?page=film&t=x">X</a> <a href="?page=film&t=y">Y</a> <a href="?page=film&t=z">Z</a> <a href="?page=film&t=recent">R&eacute;cents</a></div>';
		echo "	<div id='film' class='overflow'>";
		echo "		<p>";
		echo "<table >";
		while ($film = mysql_fetch_array($query) ){
			echo "		<tr><td class='liste'><a href='?page=film&download=".urlencode($film['file'])."'>".htmlentities(rm_ext($film['file']))."</a></td><td class='liste'><span class='size'>".size_modif($film['size'])."</span></td><td class='liste'><span class='date'>".date_modif($film['time'])."</span></td></tr>";
		}
		echo "</table>";
		echo "		</p>";
		echo "</div>";
		mysql_close();
	}
		function div_music(){
		mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
		mysql_select_db(DATABASE_NAME);
		$f=htmlspecialchars($_GET['t']);
		if ($f == ""){
			$query=mysql_query('Select * from fichier where file like "%.mp3" or file like "%.wma" or file like "%.ogg" order by file');
			}
		else if ($f=="all"){
			$query=mysql_query('Select * from fichier where file like "%.mp3" or file like "%.wma" or file like "%.ogg" order by file');
			}
		else if ($f=="recent"){
			$query=mysql_query('Select * from fichier where file like "%.mp3" or file like "%.wma" or file like "%.ogg" order by time DESC LIMIT 0 , 10');
			}
		else if ($f=="0"){
			$query=mysql_query('Select * from fichier where (file like "0%" or  file like "1%" or  file like "2%" or  file like "3%" or  file like "4%" or  file like "5%" or  file like "6%" or  file like "7%" or  file like "8%" or  file like "9%") and (file like "%.mp3" or file like "%.wma" or file like "%.ogg") order by file');
			}
		else{
			$req="Select * from fichier WHERE (file LIKE '".$f."%') and (file like '%.mp3' or file like '%.wma' or file like '%.ogg') ORDER BY file ";
			$query = mysql_query($req);
			}
		echo "	<h1>Liste des musiques</h1>";
		echo '		<div id="classement"><a href="?page=music&t=all">All</a> <a href="?page=music&t=0">0</a> <a href="?page=music&t=a">A</a> <a href="?page=music&t=b">B</a> <a href="?page=music&t=c">C</a> <a href="?page=music&t=d">D</a> <a href="?page=music&t=e">E</a> <a href="?page=music&t=f">F</a> <a href="?page=music&t=g">G</a> <a href="?page=music&t=h">H</a> <a href="?page=music&t=i">I</a> <a href="?page=music&t=j">J</a> <a href="?page=music&t=k">K</a> <a href="?page=music&t=l">L</a> <a href="?page=music&t=m">M</a> <a href="?page=music&t=n">N</a> <a href="?page=music&t=o">O</a> <a href="?page=music&t=p">P</a> <a href="?page=music&t=q">Q</a> <a href="?page=music&t=r">R</a> <a href="?page=music&t=s">S</a> <a href="?page=music&t=t">T</a> <a href="?page=music&t=u">U</a> <a href="?page=music&t=v">V</a> <a href="?page=music&t=w">W</a> <a href="?page=music&t=x">X</a> <a href="?page=music&t=y">Y</a> <a href="?page=music&t=z">Z</a> <a href="?page=music&t=recent">R&eacute;cents</a></div>';
		echo "<div id='music' class='overflow'>";
		echo "		<p>";
		echo "<table class='liste'>";
		while ($film = mysql_fetch_array($query) ){
			echo "			<tr><td><a href='?page=music&download=".urlencode($film['file'])."'>".htmlentities(rm_ext($film['file']))."</a></td><td><span class='size'>".size_modif($film['size'])."</span></td><td><span class='date'>".date_modif($film['time'])."</span></td></tr>";
		}
		echo "</table>";
		echo "		</p>";
		echo "</div>";
		mysql_close();
	}
	function div_search($type,$chaine){
		?>
		<div id="search">
			<form action='index.php?page=search' method='post'>
				<table>
					<tr>
						<td><input type="text" name="search" value=""></td><td><input type="submit" value="Cherche!"></td>
					</tr>
				</table>
			</form>
		</div>
		<div id="result" class="overflow">
			<table class="liste">
		<?php 
				if($type=='all'){
					$requete=" SELECT * FROM `fichier` WHERE `file` LIKE '%".$chaine."%'  ORDER BY file";
				}elseif($type=='music'){
					$requete=" SELECT * FROM `fichier` WHERE `file` LIKE '%".$chaine."%' and (file like '%.mp3' or file like '%.wma' or file like '%.ogg') ORDER BY file";
				}elseif($type=='film'){
					$requete="SELECT * FROM `fichier` WHERE `file` LIKE '%".$chaine."%' and (file like '%.avi' or file like '%.nrg')";
				}
		mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
		mysql_select_db(DATABASE_NAME);
		$query=mysql_query($requete);
		mysql_close();		
		while ($fichier = mysql_fetch_array($query) ){
			echo "			<tr><td><a href='?page=search&download=".urlencode($fichier['file'])."'>".htmlentities(rm_ext($fichier['file']))."</a></td><td><span class='size'>".size_modif($fichier['size'])."</span></td><td><span class='date'>".date_modif($fichier['time'])."</span></td></tr>";
		}?>
			</table>
		</div>
		<?php 
	}
	
	function download($file){
		mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
		mysql_select_db(DATABASE_NAME);
		urldecode($file);
		$sql_query=mysql_query('select * from fichier where file="'.$file.'"');
		mysql_close();
		while ($query = mysql_fetch_array($sql_query) )
		{		
		$path=utf8_encode($query['path']);
		}
		$file2=$path."".$file;
		if ($file2 == false){
			print "Bad name of file<br />";
			print $file;
			exit();
		}
//gener header
		header("Pragma: public");                                                // vider le cache du navigateur
        header("Expires: 0");                                                    // ...
        header("Cache-Control:");                                                // ...
        header("Cache-Control: public");                                         // ... 
        header("Content-Description: File Transfer");    
		header('Content-Disposition: attachment; filename="'.$file.'";');
		header('Content-type:application/force-download');
		header("Content-Transfer-Encoding: binary");                             // methode du transfert  
        header("Content-Length: ".filesize($file2)."");                          // taille de téléchargement	
	
		$fp = fopen($file2, "r");
		$nb_user+=1;
		while (!feof($fp))	{
		    echo fread($fp, 61440);
		    flush(); // this is essential for large downloads
		    sleep(1*$nb_user);
		}
		fclose($fp);
		$nb_user-=1;
	}

	function add_fichier($rep){
		mysql_connect(DATABASE_ADDRESS, DATABASE_USER, DATABASE_PASS);
		mysql_select_db(DATABASE_NAME);
		$dir = opendir($rep);
			$pathrep = $rep;
			while ($file = readdir($dir)) {
				if(is_file($rep.$file)){
					$i = count($share_file);
					$size =filesize($rep.$file);
					$time = filectime($rep.$file);
					$requete2='insert into fichier values ("'.utf8_decode($file).'","'.$size.'","'.$time.'","'.utf8_decode($pathrep).'") ';
					mysql_query($requete2);					
				}
				elseif(is_dir($rep.$file) and $file != "." and $file != ".."){
					check_recurse_folder($rep.$file."/",$share_file);
				}
			}
		mysql_close();
	}
